// pages/addPrize/index.js
import {
  UserAccountModel
} from '../../models/userAccount.js'
let userAccountModel = new UserAccountModel()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activity_id: 0,
    num: 0,
    data:{
      "item[0].name": "a",
      "item[0].rate": "1",
      "item[1].name": "b",
      "item[1].rate": "2"
    },
    prizeList:[
      
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getPrizeList()
    console.log(this.data.prizeList)
  },
  getPrizeList(){
    wx.showLoading({
      title: '加载中',
    })
    let account = userAccountModel.getPrizeList()
    account.then(
      res => {
        console.log(res)
        if (res.code == 1) {
          wx.hideLoading();
          this.setData({
            prizeList: res.data
          })
        } else {
          wx.hideLoading();
        }
      }
    ).catch(e => {
      wx.hideLoading();
      console.log(e)
    });
  },
  handleData(datas){
    let arr = []
    let o = {}
    for (let data in datas) {
      if (data.startsWith("item")) {

        let key = this.getCaption(data)
        let value = datas[data]
        let index = data.replace(/[^0-9]/ig, "");

        // console.log(o, index, arr.length, index <= arr.length,arr)
        if (index <= arr.length) {
          o[key] = value
        } else {
          arr.push(o)
          o = {}
          o[key] = value
        }

      }

    }
    arr.push(o)
    return arr
  },
  getCaption(obj){
    var index = obj.lastIndexOf("\.");
    obj=obj.substring(index + 1, obj.length);
    // console.log(obj);
    return obj;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  formSubmit(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    console.log(this.handleData(e.detail.value))
    this.editPrize(this.handleData(e.detail.value))
  }, 
  editPrize(data) {
    wx.showLoading({
      title: '添加中',
    })

    let account = userAccountModel.editPrize(data)
    account.then(
      res => {
        console.log(res)
        if (res.code == 1) {
          wx.hideLoading();

          wx.showToast({
            title: '修改成功',
          })
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '修改失败 ' + res.message,
          })

        }
      }
    ).catch(e => {
      wx.hideLoading();
      console.log(e)
    });
  },
})